package cn.orangeframe.neon.application.run.async;

import cn.orangeframe.neon.application.run.WorkflowExecutor;
import cn.orangeframe.neon.application.tasks.WorkflowSystemTask;
import cn.orangeframe.neon.domain.model.TaskModel;
import cn.orangeframe.neon.domain.model.WorkflowModel;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
public class AsyncTaskExecuteListener {

    private final WorkflowExecutor workflowExecutor;

    public AsyncTaskExecuteListener(WorkflowExecutor workflowExecutor) {
        this.workflowExecutor = workflowExecutor;
    }

    @Async
    @EventListener(AsyncTaskExecuteEvent.class)
    public void onTaskStart(AsyncTaskExecuteEvent event) {
        try {
            WorkflowSystemTask systemTask = event.getSystemTask();
            WorkflowModel workflowModel = event.getWorkflowModel();
            TaskModel taskModel = event.getTaskModel();
            taskModel.setStartTime(System.currentTimeMillis());
            systemTask.execute(workflowModel, taskModel, workflowExecutor);
            workflowExecutor.decide(workflowModel);
        } finally {
            event.getTaskModel().getLatch().countDown();
        }
    }
}
